<template>
  <div class="my-projectPayment basic-from" v-if="dialogVisible">
    <v-dialog smallPadding :title="isAdd ? '新增' : '编辑'" :show.sync="dialogVisible" width="1200px" @beforeClose="beforeClose" :close-on-click-modal="false">
      <div class="card-box p0">
        <div class="card-title">合同信息</div>
        <el-form ref="projectContract" :model="projectForm.projectContract" class="form-wrap" size="small" :rules="contract_rules" label-position="top">
          <el-form-item label="合同编号" prop="contractNum">
            <el-input v-halfCharCode v-if="isAdd" readonly suffix-icon="el-icon-search" v-model="projectForm.projectContract.contractNum" maxlength="100" placeholder="请输入合同编号" @click.native="handleClickContractNum" />
            <el-input v-halfCharCode v-else readonly v-model="projectForm.projectContract.contractNum" maxlength="100" placeholder="请输入合同编号" />
          </el-form-item>
          <el-form-item label="合同类型" prop="contractType">
            <el-input v-halfCharCode readonly v-model="projectForm.projectContract.contractType" maxlength="100" placeholder="请输入合同类型" />
          </el-form-item>
          <el-form-item label="合同总金额(元)" prop="contractAmount">
            <el-input v-halfCharCode readonly v-model="projectForm.projectContract.contractAmount" maxlength="100" placeholder="请输入合同总金额" />
          </el-form-item>
          <el-form-item label="签订日期" prop="contractDate">
            <el-input v-halfCharCode readonly v-model="projectForm.projectContract.contractDate" maxlength="100" placeholder="请选择签订日期" />
          </el-form-item>
          <el-form-item label="乙方单位名称" prop="partybUnit">
            <el-input v-halfCharCode readonly v-model="projectForm.projectContract.partybUnit" maxlength="100" placeholder="请输入乙方单位名称" />
          </el-form-item>
        </el-form>
        <div class="card-title">本次付款信息</div>
        <el-form ref="projectPayment" :model="projectForm.projectPayment" class="form-wrap" size="small" :rules="payment_rules" label-position="top">
          <el-form-item label="第几次" prop="payNum">
            <el-input v-halfCharCode readonly v-model="projectForm.projectPayment.payNum" maxlength="100" placeholder="请输入第几次">
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="付款支付日期" prop="payDate">
            <el-date-picker v-model="projectForm.projectPayment.payDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择付款支付日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="支付金额(元)" prop="payAmount">
            <el-input v-halfCharCode v-model="projectForm.projectPayment.payAmount" maxlength="18" placeholder="请输入支付金额" />
          </el-form-item>
          <el-form-item label="意见" class="full" prop="remarks">
            <el-input v-halfCharCode v-model="projectForm.projectPayment.remarks" maxlength="1000" placeholder="请输入意见" />
          </el-form-item>
        </el-form>
        <div class="card-title">附件</div>
        <div class="handling-opinions">
          <v-upload ref="paymentUpload" :busId="projectForm.projectPayment.projectPaymentId" modelType="projectPayment" @onSuccess="onSuccess" isShowFileList :isView="false" multiple v-model="fileList" />
        </div>
      </div>
      <span slot="foot">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button v-throttle="[commit]">保 存</el-button>
      </span>
    </v-dialog>
    <!--        合同弹框-->
    <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleClickAdd" :filterItemList="filterItemList" />
  </div>
</template>

<script>
import { doubleValidate } from '~/utils/validate.js'
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { get, save, update, validateCode } from '../api/payment'
export default {
  name: "edit-data",
  mixins: [BaseLoad],
  created () {
    this.contractTypes = this.getDict("epc_contract_type")
  },
  data () {
    return {
      dialogVisible: false,
      isAdd: true,
      projectForm: {
        projectContract: {
          projectContractId: '',
          projectId: '',
          projectPaymentId: '',
          contractNum: '',
          contractType: '',
          contractAmount: '',
          contractDate: '',
          partybUnit: ''
        },
        projectPayment: {
          payNum: '',
          payDate: '',
          payAmount: '',
          remarks: '',
          projectContractId: '',
          projectId: '',
          projectPaymentId: '',
        }
      },
      // 选择弹窗属性数据
      chooseDialogAttrs: {},
      contractTypes: [],
      fileList: [],
      contract_rules: {
        contractType: [{ required: false, message: '请输入合同类型', trigger: 'blur' }]
      },
      payment_rules: {
        payNum: [{ required: true, message: '请输入第几次', trigger: 'blur' }],
        payDate: [{ required: true, message: '请输入付款支付日期', trigger: 'blur' }],
        payAmount: [{ required: true, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }]
      }
    }
  },
  computed: {
    filterItemList () {
      return [
        {
          label: "单位名称",
          inputType: "input",
          name: "partybUnit",
        }
      ]
    }
  },
  methods: {
    //打开弹框
    show (item) {
      this.dialogVisible = true
      if (item) {
        this.isAdd = false
        this.projectForm.projectPayment.projectPaymentId = item
        get(item).then(res => {
          if (res.data.code === 0) {
            this.projectForm.projectContract = res.data.data.projectContract
            this.projectForm.projectContract.contractType = this.getCardTypeValue(res.data.data.projectContract.contractType, this.contractTypes)
            this.projectForm.projectPayment = res.data.data.projectPayment
          } else {
            this.$message.warning('暂未获取到数据！')
          }
        })
      }
    },
    //关闭弹框
    beforeClose (done) {
      this.$emit('beforeClose')
    },
    //取消
    handleCancel () {
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    //保存
    commit () {
      const projectContract = new Promise((resolve, reject) => {
        this.$refs['projectContract'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const projectPayment = new Promise((resolve, reject) => {
        this.$refs['projectPayment'].validate((valid) => {
          if (valid) resolve();
        })
      })
      if (Number(this.projectForm.projectPayment.payAmount) <= 0) {
        this.$message.warning('温馨提示：请完善支付金额，且支付金额必须大于0！')
        this.projectForm.projectPayment.payAmount = ''
      } else {
        Promise.all([projectContract, projectPayment]).then(() => {
          validateCode({ "conId": this.projectForm.projectPayment.projectContractId, "paymentAmount": this.projectForm.projectPayment.payAmount, "payId": this.projectForm.projectPayment.projectPaymentId }).then(res => {
            if (res.data.code === 0) {
              let type = res.data.data.type
              if (type == '1') {
                // this.$message.success(res.data.data.msg)
                this.$refs.paymentUpload.submit()
              } else if (res.data.data.type == '2') {
                this.$message.warning(res.data.data.msg)
                this.$refs.paymentUpload.submit()
              } else if (res.data.data.type == '3') {
                return this.$message.error(res.data.data.msg)
              }
            }
          })
        })
      }
    },
    //文件上传
    onSuccess (response, file, fileList) {
      //文件上传成功，开始保存表单
      if (fileList !== undefined && fileList.length > 0) {
        if (response.data) {
          this.projectForm.projectPayment.projectPaymentId = response.data
          this.saveFormData(response.data)
        } else {
          this.err('文件上传失败')
        }
      } else {
        this.saveFormData(response.data)
      }
    },
    saveFormData () {
      this.loadAction('数据加载中')
      if (this.isAdd) {
        save(this.projectForm.projectPayment).then((rep) => {
          this.loadClose()
          this.$message.success("保存成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("保存失败");
        })
      } else {
        update(this.projectForm.projectPayment).then((rep) => {
          this.loadClose()
          this.$message.success("修改成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("修改失败");
        });
      }
    },
    //对应value取label
    getCardTypeValue (num, sum) {
      let arr = sum.filter(e => e.value === num)
      if (arr.length > 0) {
        return arr[0].label
      } else {
        return num
      }
    },
    //选择合同编号
    handleClickContractNum () {
      const contractTypeFormatter = (row, column, cellValue) => {
        if (this.contractTypes.length === 0) return '';
        let type = this.contractTypes.find(item => item.value == cellValue)
        return type ? type.label : '';
      }
      this.chooseDialogAttrs = {
        title: '选择合同',
        placeholder: '请输入合同编号',
        url: '/api/epcprojectpayment/contractPage',
        primaryKey: 'contractNum',
        searchKey: 'contractNum',
        width: "1200px",
        showData: [
          { prop: 'contractNum', label: '合同编号', width: '200', align: 'center' },
          { prop: 'contractType', label: '合同类型', width: '200', align: 'center', formatter: contractTypeFormatter },
          { prop: 'contractAmount', label: '合同总金额', width: '200', align: 'center' },
          { prop: 'contractDate', label: '签订日期', width: '200', align: 'center' },
          { prop: 'partybUnit', label: '乙方单位名称', width: '200', align: 'center' }
        ]
      }
      this.$nextTick(() => {
        this.$refs.chooseDialog.show()
      })
    },
    //合同编号确定
    handleClickAdd (item) {
      if (this.projectForm.projectContract.contractNum) {
        this.$confirm('一次只能添加一条数据，该操作将覆盖上条数据,是否继续?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.projectForm.projectContract = item
          if (item.accumulatedPaymentTimes) {
            this.projectForm.projectPayment.payNum = item.accumulatedPaymentTimes + 1
          } else {
            this.projectForm.projectPayment.payNum = 1
          }

          this.projectForm.projectPayment.projectId = item.projectId
          this.projectForm.projectPayment.projectContractId = item.projectContractId
          this.projectForm.projectContract.contractType = this.getCardTypeValue(item.contractType, this.contractTypes)
          this.$message.success('添加成功！')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.projectForm.projectContract = item
        if (item.accumulatedPaymentTimes) {
          this.projectForm.projectPayment.payNum = item.accumulatedPaymentTimes + 1
        } else {
          this.projectForm.projectPayment.payNum = 1
        }

        this.projectForm.projectPayment.projectId = item.projectId
        this.projectForm.projectPayment.projectContractId = item.projectContractId
        this.projectForm.projectContract.contractType = this.getCardTypeValue(item.contractType, this.contractTypes)
        this.$message.success('添加成功！')
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.handling-opinions {
  padding: 20px;
}
</style>
